<template>
  <div>
    <form style="width: 500px; margin: 50px auto" @submit.prevent="login">
      <div class="form-group">
        <label for="username">用户名：</label>
        <input
          class="form-control"
          placeholder="请输入用户名"
          type="text"
          v-model="username"
        />
      </div>
      <div class="form-group">
        <label for="password">密码：</label>
        <input
          class="form-control"
          type="password"
          v-model="password"
          placeholder="请输入密码"
        />
      </div>
      <button class="btn btn-primary btn-lg" style="width: 500px">登录</button>
    </form>
  </div>
</template>
<script>
import { mapState, mapMutations } from "vuex";
export default {
  data() {
    return {
      username: "",
      password: "",
    };
  },
  created() {
    if (this.user) {
      this.$router.push("/");
    }
  },
  computed: {
    ...mapState(["user"]),
  },
  methods: {
    login() {
      // 原
      // this.axios
      //   .post("/api/user/login", {
      //     username: this.username,
      //     password: this.password,
      //   })
      //   .then((res) => {
      //     console.log(res);
      //     if (res.data.code == 200) {
      //       this.saveUser(res.data.data);
      //       this.$router.push("/");
      //     }
      //   });

      this.axios
        .post("/api/user/login", {
          username: this.username,
          password: this.password,
        })
        .then((res) => {
          console.log(res);
          if (res.data.code == 200) {
            this.saveUser(res.data.data);
            this.$router.push("/");
          }
        });
    },
    ...mapMutations(["saveUser"]),
  },
};
</script>
